package com.panshi.hujin2.httpcrawler.util.outlook;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.panshi.hujin2.httpcrawler.domain.outlook.OutlookAttachmentDo;
import com.panshi.hujin2.httpcrawler.domain.outlook.OutlookEmailDo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;


/**
 * 微软单封邮件解析工具
 * @Author: wangxl
 * @Date: 2018/11/22 9:08
 */
public class OutlookEmailParseUtil {

    private static Logger logger = LoggerFactory.getLogger(OutlookEmailParseUtil.class);

    /**
     * 单封邮件内容请求返回解析数据
     * @param responseContent 邮件内容集合
     * @return
     */
    public static OutlookEmailDo parseOneEmail(String responseContent){

        logger.info("解析单封邮件内容：");

        JsonParser jsonParser = new JsonParser();
        //转换json对象
        JsonObject jsonObject = jsonParser.parse(responseContent).getAsJsonObject();

        JsonObject responseMessages = jsonObject.getAsJsonObject("Body").getAsJsonObject("ResponseMessages");

        JsonArray items1Array = responseMessages.getAsJsonArray("Items");

        JsonObject item1 = items1Array.get(0).getAsJsonObject();

        JsonArray items2Array = item1.getAsJsonArray("Items");

        JsonObject item2 = items2Array.get(0).getAsJsonObject();

        //download item id
        JsonArray attachments = item2.getAsJsonArray("Attachments");
        List<OutlookAttachmentDo> list = new ArrayList<OutlookAttachmentDo>();
        OutlookAttachmentDo attachmentDo = null;
        if(attachments!=null && attachments.size()>0) {
            for (int i = 0; i < attachments.size(); i++) {
                JsonObject a = attachments.get(i).getAsJsonObject();
                //附件下载ID
                String attachmentId = a.getAsJsonObject("AttachmentId").get("Id").toString();
                attachmentId = attachmentId.replaceAll("\"", "");

                //附件名称
                String attachmentName = a.get("Name").toString();
                attachmentName = attachmentName.replaceAll("\"", "");

                attachmentDo = new OutlookAttachmentDo(attachmentId,attachmentName,null);
                list.add(attachmentDo);
            }
        }
        String subject = item2.get("Subject").toString();

        JsonObject normalizedBody = item2.getAsJsonObject("NormalizedBody");

        String bodyType = normalizedBody.get("BodyType").toString();
        String value = normalizedBody.get("Value").toString();

        return new OutlookEmailDo(subject,bodyType,value,list);
    }

    public static void main(String args[]){

    }

}
